#include <iostream>
#include <queue>
#include <map>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <unordered_set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
const int N=1e6+10;
char s[N];
int a[6][N];
unordered_map <char,int> mp;
int main()
{
	int t;
	cin>>t;
	mp['A']=1;
	mp['B']=10;
	mp['C']=100;
	mp['D']=1000;
	mp['E']=10000;
	while(t--)
	{
		int n;
		scanf("%s",s+1);
	    int len=strlen(s+1);
	    for(int i=1;i<=len;i++)
	    {
	    	for(int j=0;j<5;j++)
	    	{
	    		a[j][i]=a[j][i-1];
			}
	    	a[s[i]-'A'][i]++;
		}
		ll ans=mp[s[len]];
		char mc=s[len];
		s[len+1]='A';
		s[len+2]='\0';
		vector<int> v;
		v.push_back(len+1);
		v.push_back(len);
		for(int i=len-1;i>0;i--)
		{
			if(s[i]<mc)
			{
				ans-=mp[s[i]];
			 }
			 else
			 {
			 	ans+=mp[s[i]];
			 	mc=s[i];
			 	v.push_back(i);
			 }
		}
		s[0]='E';
		v.push_back(0);
		ll sum=ans;
		int idx=1;
//		cout<<ans<<endl;
		for(int i=len;i>=1;i--)
		{
			if(s[i]==s[v[idx]])
			{
				sum=max(sum,ans-mp[s[i]]+mp[s[v[idx+1]]]);
				ll sum1=0;
				for(int j=s[i]-'A'-1; j>=s[v[idx-1]]-'A';j--)
				{
					sum1=ans-mp[s[i]]+mp[j+'A'];
					for(int k=j;k<s[i]-'A';k++)
					{
						sum1=sum1+2*(ll)mp[k+'A']*(a[k][i]-a[k][v[idx+1]]); 
					}
					sum=max(sum,sum1);
				}
				
				idx++;
			}
			else
			{
				ll sum1=ans+mp[s[i]]+mp[s[v[idx]]];
				sum=max(sum,sum1);
			}
		}
		ans=max(ans,sum);
		cout<<ans<<endl;
//		for(int i=0;i<=5;i++)
//		{
//			for(int j=0;j<=len+1;j++) a[i][j]=0;
//		}
	
	}

	return 0;
}

